window.addEventListener('load', () => {
  (function () {
    let position = 'absolute'
    let snakeArr = []
    function Snake(obj) {
      obj = obj || {}
      this.width = obj.width || 20
      this.height = obj.height || 20
      // 蛇面对，移动的方向
      this.facing = obj.facing || 'right'
      this.body = [{
          x: 3,
          y: 2,
          color: 'red'
        },
        {
          x: 2,
          y: 2,
          color: 'blue'
        },
        {
          x: 1,
          y: 2,
          color: 'blue'
        },
      ]
    }
    // 渲染
    Snake.prototype.render = function (map) {
      
      delSnake()
      this.body.forEach(item => {
        let div = document.createElement('div')
        map.appendChild(div)

        snakeArr.push(div)
        // 设置蛇样式
        div.style.position = position
        div.style.left = item.x * this.width + 'px'
        div.style.top = item.y * this.height + 'px'
        div.style.width = this.width + 'px'
        div.style.height = this.height + 'px'
        div.style.backgroundColor = item.color
      });
    }

    function delSnake() {
      for (let i = snakeArr.length - 1; i >= 0; i--) {
        snakeArr[i].parentNode.removeChild(snakeArr[i])
        snakeArr.splice(i, 1)
      }
    }

    // 移动
    Snake.prototype.move = function (food, map) {
      for (let i = this.body.length - 1; i > 0; i--) {
        this.body[i].x = this.body[i - 1].x
        this.body[i].y = this.body[i - 1].y
      }
      // 判断蛇的移动方向
      let header = this.body[0]
      switch (this.facing) {
        case 'right':
          header.x += 1
          break
        case 'left':
          header.x -= 1
          break
        case 'top':
          header.y += 1
          break
        case 'bottom':
          header.y -= 1
          break
      }

      let headerX = header.x * this.width
      let headerY = header.y * this.height
      if (headerX === food.x && headerY === food.y) {
        // 增加蛇的长度
        let lastNode = this.body[this.body.length - 1]
        this.body.push({
          x: lastNode.x,
          y: lastNode.y,
          color: lastNode.color,
        })
        // 重新生成食物
        food.render(map)
      }
    }

    window.Snake = Snake
  })()

  // 测试
  // let map = document.getElementById('map')
  // let snake = new Snake()
  // snake.render(map)
})